VARIABLE SCOPE AND GLOBAL/LOCAL VARIABLES

Variable scope in Python refers to the accessibility or visibility of variables within different parts of the code. The scope of a variable determines where the variable can be accessed and modified. In Python, there are two main types of variable scope:

  1. Global Variables:

    • A global variable is defined outside any function or code block and is accessible throughout the entire program.
    • Global variables have global scope and can be accessed from any part of the code, including within functions.
    • To create a global variable, simply define it outside any function.
    python
    # Global variable global_var = 10 def my_function(): # Accessing the global variable print(global_var) my_function() # Output: 10
    • If you want to modify a global variable from within a function, you need to use the global keyword before the variable name inside the function.
    python
    global_var = 10 def modify_global(): global global_var global_var = 20 print(global_var) # Output: 10 modify_global() print(global_var) # Output: 20
  2. Local Variables:

    • A local variable is defined within a function and is accessible only within that specific function.
    • Local variables have local scope, meaning they are limited to the block where they are defined and cannot be accessed outside that function.
    • When you create a variable inside a function, it is considered local by default.
    python
    def my_function(): # Local variable local_var = 5 print(local_var) my_function() # Output: 5 # Trying to access the local variable outside the function will raise an error # print(local_var) # Raises NameError: name 'local_var' is not defined
    • Local variables are created when the function is called and are destroyed when the function returns or completes its execution.
    python
    def example_function(): x = 10 print(x) example_function() # Output: 10 # The local variable x is destroyed after the function call, so trying to access it will raise an error # print(x) # Raises NameError: name 'x' is not defined

Understanding variable scope is essential to avoid naming conflicts and to ensure that variables are used in the intended parts of your code. Always be mindful of the scope of variables when working with functions and blocks of code in Python.